package com.zygk.xmpp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.mabeijianxi.smallvideorecord2.LocalMediaCompress;
import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;
import com.mabeijianxi.smallvideorecord2.model.AutoVBRMode;
import com.mabeijianxi.smallvideorecord2.model.LocalMediaConfig;
import com.mabeijianxi.smallvideorecord2.model.MediaRecorderConfig;
import com.mabeijianxi.smallvideorecord2.model.OnlyCompressOverBean;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.DateUtil;
import com.zygk.library.util.FileUtil;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.xmpp.R;
import com.zygk.xmpp.R2;
import com.zygk.xmpp.adapter.ChatAdapter;
import com.zygk.xmpp.adapter.OldChatAdapter;
import com.zygk.xmpp.constant.Urls;
import com.zygk.xmpp.dao.MsgDbHelper;
import com.zygk.xmpp.dao.UploadLogic;
import com.zygk.xmpp.model.M_ChatItem;
import com.zygk.xmpp.model.M_Msg;
import com.zygk.xmpp.model.apimodel.APIM_uploadFile;
import com.zygk.xmpp.util.Constants;
import com.zygk.xmpp.util.HttpRequest;
import com.zygk.xmpp.view.ChatListView;
import com.zygk.xmpp.view.RecordButton;
import com.zygk.xmpp.view.expression.ExpressionView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.zygk.xmpp.xmpp.XMPP;
import com.zygk.xmpp.xmpp.XmppConnection;
import java.util.ArrayList;
import java.util.List;
import org.jivesoftware.smack.XMPPConnection;
import org.json.JSONObject;

/**
 * 聊天界面
 * created by Djy
 * 2018/7/18 0018 下午 6:07
 */
public class ChatActivity extends BaseActivity {

  @BindView(R2.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R2.id.listView) ChatListView listView;
  @BindView(R2.id.et_msg) EditText etMsg;
  @BindView(R2.id.recordBtn) RecordButton recordBtn;
  @BindView(R2.id.ll_bottom) LinearLayout llBottom;
  @BindView(R2.id.ll_more) LinearLayout llMore;
  @BindView(R2.id.expressionView) ExpressionView expressionView;
  @BindView(R2.id.iv_voice) ImageView ivVoice;
  @BindView(R2.id.ll_input) LinearLayout llInput;
  @BindView(R2.id.iv_more) ImageView ivMore;

  private int chatType = M_ChatItem.CHAT;
  private List<M_ChatItem> msgList = new ArrayList<>();
  private OldChatAdapter adapter;
  private String chatName;
  private List<M_ChatItem> chatItems = new ArrayList<>();

  @Override public void setContentView() {
    setContentView(R.layout.xmpp_activity_chat);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    chatName = Constants.XMPP_USERNAME;
    expressionView.setEditText(etMsg);
    XMPP.setReceiver(chatName, chatType);
    adapter = new OldChatAdapter(this, mContext, chatName);
    listView.setAdapter(adapter);
    registerReceiver(new String[] {
        Constants.BROADCAST_CHAT_NEW_MSG
    });

    getData();
    initImagePickerSingle(false);
  }

  private void getData() {
    chatItems = MsgDbHelper.getInstance(getApplicationContext()).getChatMsg(chatName);
    adapter.clear();
    adapter.addAll(chatItems);
    adapter.notifyDataSetChanged();
    listView.setSelection(adapter.getCount() + 1);
  }

  private void initView() {
  }

  private void initListener() {
    etMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
      @Override public void onFocusChange(View v, boolean hasFocus) {
        expressionView.setVisibility(View.GONE);
      }
    });

    etMsg.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        //判断是否是“完成”键
        if (i == EditorInfo.IME_ACTION_SEND) {
          //隐藏软键盘
          InputMethodManager imm = (InputMethodManager) textView.getContext()
              .getSystemService(Context.INPUT_METHOD_SERVICE);
          if (imm.isActive()) {
            imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
          }

          // TODO: 2018/7/18 0018  发送消息
          ToastUtil.showMessage(mContext, etMsg.getText().toString());
          if (!StringUtils.isBlank(etMsg.getText().toString())) {     //文本不为空，直接发文本消息
            XMPP.sendTextMsg(etMsg.getText().toString(), chatType);
            etMsg.setText("");
          }
          return true;
        }
        return false;
      }
    });

    recordBtn.setOnFinishedRecordListener(new RecordButton.OnFinishedRecordListener() {
      @Override public void onFinishedRecord(String audioPath, int time) {
        if (audioPath != null) {
          XMPP.sendRecordMsg(audioPath, chatType);
        } else {
          ToastUtil.showMessage(mContext, "发送失败");
        }
      }
    });
  }

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @OnClick({
      R2.id.ll_back, R2.id.iv_voice, R2.id.iv_expression, R2.id.iv_more, R2.id.tv_tack_pic,
      R2.id.tv_choose_pic, R2.id.tv_file, R2.id.tv_location, R2.id.tv_recorder
  }) public void onViewClicked(View view) {
    int id = view.getId();
    if (id == R.id.ll_back) {
      finish();
    } else if (id == R.id.iv_voice) {
      if (recordBtn.getVisibility() == View.GONE) {   // 从文本输入模式切换到语音输入模式
        llInput.setVisibility(View.GONE);
        recordBtn.setVisibility(View.VISIBLE);
        InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etMsg.getWindowToken(), 0);
        ivVoice.setImageResource(R.mipmap.xmpp_icon_keyboard);
      } else if (llInput.getVisibility() == View.GONE) { // 从语音输入模式切换到文本输入模式
        llInput.setVisibility(View.VISIBLE);
        recordBtn.setVisibility(View.GONE);
        ivVoice.setImageResource(R.mipmap.xmpp_icon_voice);
      }
    } else if (id == R.id.iv_expression) {
      if (expressionView.getVisibility() == View.GONE) {
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
        expressionView.setVisibility(View.VISIBLE);
        llMore.setVisibility(View.GONE);
      } else {
        expressionView.setVisibility(View.GONE);
      }
      if (llInput.getVisibility() == View.GONE) {
        llInput.setVisibility(View.VISIBLE);
        recordBtn.setVisibility(View.GONE);
      }
    } else if (id == R.id.iv_more) {
      if (llMore.getVisibility() == View.GONE) {
        InputMethodManager inputMethodManager =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
        llMore.setVisibility(View.VISIBLE);
        expressionView.setVisibility(View.GONE);
      } else {
        llMore.setVisibility(View.GONE);
      }
    } else if (id == R.id.tv_tack_pic) {
      takePic(1, null);
    } else if (id == R.id.tv_choose_pic) {
      choosePic(1, null);
    } else if (id == R.id.tv_file) {

    } else if (id == R.id.tv_location) {

    } else if (id == R.id.tv_recorder) {
      // 录制
      MediaRecorderConfig config = new MediaRecorderConfig.Buidler().fullScreen(false)
          .smallVideoWidth(360)
          .smallVideoHeight(480)
          .recordTimeMax(10000)
          .recordTimeMin(3000)
          .maxFrameRate(20)
          .videoBitrate(600000)
          .captureThumbnailsTime(0)
          .build();
      MediaRecorderActivity.goSmallVideoRecorder(this, VideoPlayerActivity.class.getName(), config);
      // 选择本地视频压缩
      //LocalMediaConfig.Buidler buidler = new LocalMediaConfig.Buidler();
      //final LocalMediaConfig config = buidler
      //    .setVideoPath("")
      //    .captureThumbnailsTime(1)
      //    .doH264Compress(new AutoVBRMode())
      //    .setFramerate(15)
      //    .setScale(1.0f)
      //    .build();
      //OnlyCompressOverBean onlyCompressOverBean = new LocalMediaCompress(config).startCompress();
    }
  }

  ArrayList<ImageItem> images = null;

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
      //添加图片返回
      if (data != null && requestCode == REQUEST_CODE_SELECT) {
        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
        UploadLogic.upload(mContext, images.get(0).path, Urls.UPLOAD_IMAGE,
            new HttpRequest.HttpCallback() {
              @Override public void onStart() {
                showPd();
              }

              @Override public void onSucceed(Object obj) {
                APIM_uploadFile result = (APIM_uploadFile) obj;
                XMPP.sendImgMsg(result.getResults(), chatType);
              }

              @Override public void onFailed() {
                ToastUtil.showNetErrorMessage(mContext);
              }

              @Override public void onFinish() {
                dismissPd();
              }
            });
      }
    }
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    if (intent == null || StringUtils.isBlank(intent.getAction())) {
      return;
    }
    //收到新消息
    if (Constants.BROADCAST_CHAT_NEW_MSG.equals(intent.getAction())) {
      getData();
      MsgDbHelper.getInstance(getApplicationContext()).updateChatMsg(chatName);
    }
  }
}
